package com.app.xinfadi.widget.image_browser;

/**
 * Function:
 * <br/>
 * Create on:2015/8/5 16:18
 * <br/>
 * Author:WuTengFei
 */

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.app.xinfadi.R;
import com.app.xinfadi.base.BaseActivity;
import com.app.xinfadi.util.LogUtil;
import com.app.xinfadi.widget.image_browser.view.GridViewSquareImageBrowserAdapter;
import com.app.xinfadi.widget.image_browser.view.ImageBrowserAdapter;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.ValueAnimator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import de.greenrobot.event.EventBus;


/**
 * 图片浏览器
 * <p/>
 * browser_type <br/>
 * 0 拍照和相册 <br/>
 * selected_size 已经选择图片数量
 *
 * @author WuTengFei <br/>
 * @Function: TODO <br/>
 * @date 2015-2-10 下午2:23:12 <br/>
 */
public class ImageBrowserActivity extends BaseActivity implements ImageBrowserPopupWindow.OnImageDirSelected {
    public final static int IMAGE_EXPORE = 0;// 拍照和相册
    public final static int SELECTED_MAX_SIZE = 9;
    public int maxSize;
    protected int totalCount;
    protected int mPicsSize;
    protected File mImgDir;
    protected int currentSize;
    /**
     * browser_type<br/>
     * 0 拍照和相册 <br/>
     * 1 从陪护报告中读取资料
     */
    private int browser_type;
    private GridView mGirdView;
    private TextView mChooseDir;
    private TextView mPreview_tv;
    private RelativeLayout mBottomLy;
    private ProgressDialog mProgressDialog;
    /**
     * 临时的辅助类，用于防止同一个文件夹的多次扫描
     */
    private HashSet<String> mDirPaths = new HashSet<String>();
    /**
     * 扫描拿到所有的图片文件夹
     */
    private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();
    /**
     * 所有的图片
     */
    private ArrayList<String> mImgs;
    private GridViewSquareImageBrowserAdapter gridViewSquareImageAdapter;
    private ImageBrowserPopupWindow imageBrowserPopupWindow;
    private int[] mBottomLyPosition;
    private String TAG = "ImageBrowserActivity";
    private String photoPath = null;
    private int selected_size = 0; // 接受到的图片数量
    private ObjectAnimator popAnimatorIn;
    private ObjectAnimator popAnimatorOff;
    private String[] mImgsPaths;
    private boolean popwindow_isShowing = false;
    //	private Handler mHandler = new Handler() {
//		public void handleMessage(android.os.Message msg) {
//			mProgressDialog.dismiss();
//			// 为View绑定数据
//			data2View();
//			// 初始化展示文件夹的popupWindw
//			// initListDirPopupWindw();
//		}
//	};
    private MyHandler mHandler = new MyHandler(this);
    private TextView common_titlebar_add;
    private boolean myViewIsVisiable = false;
    private ObjectAnimator myViewAnimatorIn;
    private ObjectAnimator myViewAnimatorOff;
    private boolean myViewIsShowing = false;
    private ListView imageBrowserListView;
    private int imageBrowserListHeight = -1;
    private ImageBrowserAdapter imageBrowserAdapter;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.image_browser);
        getExtra();
        initTitle();
        initView();
        if (browser_type == IMAGE_EXPORE) {
            getImages();
        }
    }

    private void initTitle() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("图片");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        common_titlebar_add = (TextView) findViewById(R.id.common_titlebar_add);
        common_titlebar_add.setVisibility(View.VISIBLE);
        common_titlebar_add.setOnClickListener(this);
        common_titlebar_add.setEnabled(false);
    }

    private void getExtra() {
        selected_size = getIntent().getIntExtra("selected_size", 0);
        browser_type = getIntent().getIntExtra("browser_type", IMAGE_EXPORE);
        maxSize = getIntent().getIntExtra("max_size", SELECTED_MAX_SIZE);
    }

    @SuppressLint("NewApi")
    private void initView() {
        mGirdView = (GridView) findViewById(R.id.id_gridView);
        mChooseDir = (TextView) findViewById(R.id.id_choose_dir);
        mPreview_tv = (TextView) findViewById(R.id.preview_tv);
        mPreview_tv.setOnClickListener(this);
        mBottomLy = (RelativeLayout) findViewById(R.id.id_bottom_ly);
        mBottomLy.setOnClickListener(this);
//        initImageBrowserListView();
    }

    private void initImageBrowserListView() {
        if (imageBrowserListView == null) {
            imageBrowserListView = (ListView) findViewById(R.id.imageBrowserListView);
            imageBrowserListHeight = (int) (myApplication.screenHeight * 0.75);
            imageBrowserAdapter = new ImageBrowserAdapter(context, mImageFloders);
            imageBrowserListView.setAdapter(imageBrowserAdapter);
            imageBrowserListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                mImageDirSelected.selected(mImageFloders.get(position), position);
                    if (position == 0) {
                        initGridView(mImageFloders.get(position).getImagePaths(), true);
                    } else {
                        mImgs = new ArrayList<String>();
                        mImgs = getImagePathsSort(mImageFloders.get(position).getDir());
                        mImgsPaths = mImgDir.list(new FilenameFilter() {
                            @Override
                            public boolean accept(File dir, String filename) {
                                if (filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".jpeg"))
                                    return true;
                                return false;
                            }
                        });
                        initGridView(mImgs, false);
                    }
                    mChooseDir.setText(mImageFloders.get(position).getName());
                    imageBrowserListViewOutAniamtion();
                }
            });
        }
    }


    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void imageBrowserListViewInAnimation() {
        myViewAnimatorIn = ObjectAnimator.ofFloat(imageBrowserListView, "translateY",
                (myApplication.screenHeight - mBottomLy.getHeight()), myApplication.screenHeight - imageBrowserListHeight - mBottomLy.getHeight());
        myViewAnimatorIn.setDuration(350).start();
        final int currentY = imageBrowserListView.getTop();
        int currentHeight = imageBrowserListView.getLayoutParams().height;
        LogUtil.e(TAG, "BottomHeight:" + mBottomLy.getHeight() + " BottomY:" + mBottomLyPosition[1]);
        LogUtil.e(TAG, "myViewCurrentHeight:" + currentHeight + " myViewCurrentY:" + imageBrowserListView.getY());
        // 添加了addUpdateListener
        myViewAnimatorIn.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float f = (Float) animation.getAnimatedValue();
                // 通过设置view的Y轴 实现移动
//                imageBrowserPopupWindow.getContentView().setTranslationX(f - imageBrowserPopupWindow.getContentView().getTop());
//                myView.setY(f);
                ViewGroup.LayoutParams lp = imageBrowserListView.getLayoutParams();
                lp.height = mBottomLyPosition[1] - (int) f;
                imageBrowserListView.setLayoutParams(lp);
                LogUtil.d(TAG, "in y" + f + " myViewHeight:" + lp.height);

            }
        });
        myViewIsShowing = true;
    }

    private void imageBrowserListViewOutAniamtion() {
        imageBrowserListView.setVisibility(View.VISIBLE);
        myViewAnimatorIn = ObjectAnimator.ofFloat(imageBrowserListView, "translateY",
                myApplication.screenHeight - imageBrowserListHeight - mBottomLy.getHeight(), (myApplication.screenHeight - mBottomLy.getHeight()));
        myViewAnimatorIn.setDuration(350).start();
        // 添加了addUpdateListener
        final int currentY = imageBrowserListView.getTop();
        myViewAnimatorIn.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float f = (Float) animation.getAnimatedValue();
                // 通过设置view的Y轴 实现移动

//                myView.setY(f);
                ViewGroup.LayoutParams lp = imageBrowserListView.getLayoutParams();
                lp.height = mBottomLyPosition[1] - (int) f;
//                imageBrowserPopupWindow.getContentView().setTranslationX(f - imageBrowserPopupWindow.getContentView().getTop());
                imageBrowserListView.setLayoutParams(lp);
                LogUtil.d(TAG, "out  y" + f + " myViewHeight:" + lp.height);
            }
        });
        myViewIsShowing = false;

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return false;
    }


    /**
     * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中 完成图片的扫描，最终获得jpg最多的那个文件夹
     */
    private void getImages() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }
        // 显示进度条
        mProgressDialog = ProgressDialog.show(this, null, "正在加载...");

        new Thread(new Runnable() {
            @Override
            public void run() {

                String firstImage = null;

                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = context.getContentResolver();

                // 只查询jpeg和png的图片
                Cursor mCursor = mContentResolver.query(mImageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"image/jpeg"},//, "image/png"
                        // desc asc
                        MediaStore.Images.Media.DATE_MODIFIED + " desc");
                String firstPath = null;
                int i = 0;
                mImgs = new ArrayList<String>();
                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));

                    mImgs.add("file://" + path);
                    if (i == 0) {
                        firstPath = path;
                    }
                    i++;
                    // 拿到第一张图片的路径
                    if (firstImage == null)
                        firstImage = path;
                    // 获取该图片的父路径名
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    ImageFloder imageFloder = null;
                    // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        // 初始化imageFloder
                        imageFloder = new ImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }

                    String picList[] = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".jpeg")) {
                                return true;
                            }
                            return false;
                        }
                    });
                    totalCount += picList.length;
                    imageFloder.setCount(picList.length);
                    mImageFloders.add(imageFloder);

                    if (picList.length > mPicsSize) {
                        mPicsSize = picList.length;
                        mImgDir = parentFile;
                        mImgsPaths = picList;
                    }
                }
                ImageFloder firstImageFloder = new ImageFloder();
                firstImageFloder.setName("所有图片");
                firstImageFloder.setSingleDir(mImgDir.getAbsolutePath());
                firstImageFloder.setFirstImagePath(firstPath);
                firstImageFloder.setCount(totalCount);
                firstImageFloder.setImagePaths(mImgs);
                mImageFloders.add(0, firstImageFloder);
                mCursor.close();
                // 扫描完成，辅助的HashSet也就可以释放内存了
                mDirPaths = null;
                // 通知 Handler扫描图片完成
                mHandler.sendEmptyMessage(0x110);
                // 初始化 popupwindow
            }
        }).start();

    }

    /**
     * 为View绑定数据
     */
    private void data2View() {
        if (mImgs.size() < 0) {
            Toast.makeText(getApplicationContext(), "擦，一张图片没扫描到", Toast.LENGTH_SHORT).show();
            return;
        }
        initGridView(mImgs, true);
    }

    private void initGridView(ArrayList<String> imageUrl, boolean isAllImage) {
        /**
         * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
         */
        // Collections.reverse(imageUrl);
        // addPhotographImage(mImgs);
        gridViewSquareImageAdapter = new GridViewSquareImageBrowserAdapter(context, imageUrl, isAllImage, selected_size, maxSize);
        mGirdView.setAdapter(gridViewSquareImageAdapter);
        gridViewSquareImageAdapter.setOnCheckChangeListener(new GridViewSquareImageBrowserAdapter.OnCheckChangeListener() {

            @Override
            public void onCheckSize(int size) {
                currentSize = size + selected_size;
                common_titlebar_add.setEnabled(true);
                common_titlebar_add.setText("发送(" + currentSize + "/" + maxSize + ")");
                if (size == 0) {
                    common_titlebar_add.setText("发送");
                    common_titlebar_add.setEnabled(false);
                }
                mPreview_tv.setText("预览(" + currentSize + ")");
            }
        });
        gridViewSquareImageAdapter.setOnPhotographClickListener(new GridViewSquareImageBrowserAdapter.OnPhotographClickListener() {

            @Override
            public void onclick() {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 下面这句指定调用相机拍照后的照片存储的路径
                UUID uuid = UUID.randomUUID();
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera/",
                        "IMG_" + uuid + ".jpg");
                photoPath = file.getAbsolutePath();
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                ScannerFile(photoPath);
                startActivityForResult(intent, 2);
            }
        });
        mGirdView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), false, false));

    }

    @Override
    public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            /**
             * 当ListDirPopupwindow 显示时 common_titlebar_back 功能为隐藏 ListDirPopupwindow
             * v.getId() == R.id.common_titlebar_back &&
             */
            if (popwindow_isShowing) {
                imageBrowserListViewOutAniamtion();
            } else {
                finish();
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.common_titlebar_add:
//                Intent intent = new Intent();
//                intent.putStringArrayListExtra("imageUrlList", gridViewSquareImageAdapter.getClickImages());
//                setResult(0, intent);
                EventBus.getDefault().post(gridViewSquareImageAdapter.getClickImages());
                finish();
                break;
            case R.id.id_bottom_ly:
                initImageBrowserListView();
                if (!myViewIsShowing) {
                    imageBrowserListViewInAnimation();

                } else {
                    imageBrowserListViewOutAniamtion();
                }
                break;
            case R.id.preview_tv:
                if (currentSize > 0) {
                    Intent ImageExploreIntent = new Intent(context, ImageExploreActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putStringArrayList("imageUrlList", gridViewSquareImageAdapter.getClickImages());
                    bundle.putInt("currentPosition", 0);
                    ImageExploreIntent.putExtras(bundle);
                    context.startActivity(ImageExploreIntent);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void selected(ImageFloder floder, int position) {
        if (position == 0) {
            initGridView(floder.getImagePaths(), true);
        } else {
            mImgs = new ArrayList<String>();
            mImgs = getImagePathsSort(floder.getDir());
            mImgsPaths = mImgDir.list(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String filename) {
                    if (filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".jpeg"))
                        return true;
                    return false;
                }
            });
            initGridView(mImgs, false);
        }
        mChooseDir.setText(floder.getName());
        imageBrowserPopupWindow.dismiss();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        mBottomLyPosition = new int[2];
        mBottomLy.getLocationInWindow(mBottomLyPosition);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.d(TAG, resultCode + "");
        if (resultCode == RESULT_OK) {
            LogUtil.d(TAG, "拍照");
            if (photoPath != null) {
                ArrayList<String> imageList = new ArrayList<String>();
                imageList.add("file://" + photoPath);
//                Intent intent = new Intent();
//                intent.putStringArrayListExtra("imageUrlList", imageList);
//                setResult(0, intent);
                // ImageLoader.getInstance().clearMemoryCache();
                EventBus.getDefault().post(imageList);
                finish();
            }
        }
        LogUtil.e(TAG, "requestCode " + requestCode);
    }

    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

    private void ScannerFile(String savePathName) {
        MediaScannerConnection.scanFile(context, new String[]{savePathName}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                        LogUtil.e(TAG, "Scanned " + path + " uri:" + uri);
                    }
                });
    }

    /**
     * 获取目录下所有图片(按时间排序)
     *
     * @param path
     * @return
     */
    public ArrayList<String> getImagePathsSort(String path) {
        ArrayList<String> imagePaths = new ArrayList<String>();
        List<File> list = getFiles(path, new ArrayList<File>());

        if (list != null && list.size() > 0) {

            Collections.sort(list, new Comparator<File>() {
                public int compare(File file, File newFile) {
                    if (file.lastModified() < newFile.lastModified()) {
                        return 1;
                    } else if (file.lastModified() == newFile.lastModified()) {
                        return 0;
                    } else {
                        return -1;
                    }

                }
            });
            for (File file : list) {
                imagePaths.add("file://" + file.getAbsolutePath());
            }
        }

        return imagePaths;
    }

    /**
     * 获取目录下所有文件
     *
     * @param realpath
     * @param files
     * @return
     */
    public List<File> getFiles(String realpath, List<File> files) {

        File realFile = new File(realpath);
        if (realFile.isDirectory()) {
            File[] subfiles = realFile.listFiles();
            for (File file : subfiles) {
                if (file.isDirectory()) {
                    getFiles(file.getAbsolutePath(), files);
                } else {
                    files.add(file);
                }
            }
        }
        return files;
    }

    public int getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }

    static class MyHandler extends Handler {
        private final WeakReference<ImageBrowserActivity> outerClass;

        MyHandler(ImageBrowserActivity theClass) {
            outerClass = new WeakReference<ImageBrowserActivity>(theClass);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            ImageBrowserActivity theClass = outerClass.get();
            theClass.mProgressDialog.dismiss();
            // 为View绑定数据
            theClass.data2View();
        }
    }
}

